/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.jg.report.freight.information.dto.AppInfoDTO;
import org.jeecg.modules.third.openapi.OpenApiService;
import org.jeecg.modules.third.openapi.dto.report.ZjDriverDTO;
import org.jeecg.modules.third.openapi.dto.report.ZjVehicleDTO;
import org.jeecg.modules.third.openapi.dto.report.capital.CapitalDTO;
import org.jeecg.modules.third.openapi.dto.report.waybill.WaybillDTO;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReport;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverReportService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleReport;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleReportService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingPayStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @BelongsPackage: org.jeecg.modules.wlhy.report.impl
 * @Author: duanlikao
 * @CreateTime: 2023-03-08 16:08
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class ZjiaoReportService implements IReportService {
    @Resource
    private BaseReportService baseReportService;

    @Resource
    private IHyDriverService driverService;

    @Resource
    private IHyVehicleService vehicleService;


    @Resource
    private IHyDriverReportService hyDriverReportService;


    @Resource
    private IHyVehicleReportService vehicleReportService;


    @Resource
    private OpenApiService openApiService;


    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Override
    public ReportPlatformEnum getReportType() {
        return ReportPlatformEnum.REPORT_PLATFORM_ZJ;
    }

    @Override
    public void checkReport() {
        //中交兴路平台
        if(!HyCfgUtil.isUsed2("zhongjiao_report")){
            throw new JeecgBootException("中交上报未配置参数!");
        }
    }

    @Override
    public AppInfoDTO getAppInfo() {
        return null;
    }


    @Override
    public boolean report(HyShippingNote hyShippingNote) {
        return false;
    }

    @Override
    public Result reportShippingNote(HyShippingNote hyShippingNote) {
        Result result = checkDriverAndVehicle(hyShippingNote.getId());
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadZjShippingNote(hyShippingNote);
    }

    @Override
    public Result reportCapitalFlow(HyShippingNote hyShippingNote) {
        Result result = checkDriverAndVehicle(hyShippingNote.getId());
        if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
            return result;
        }

        return this.uploadZjCapitalFlow(hyShippingNote.getId());
    }


    //上报运单和资金流水前，先确认司机、车辆的上传状态
    private Result checkDriverAndVehicle(String shippingId) {

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(shippingId);
        if (null == hyShippingNote) {
            return Result.error("运单不存在");
        }

        String driverId = hyShippingNote.getDriverId();
        String vehicleId = hyShippingNote.getVehicleId();
        if (StrUtil.isEmpty(driverId)) {
            return Result.error("当前运单司机信息不存在");
        }

        if (StrUtil.isEmpty(vehicleId)) {
            return Result.error("当前运单车辆信息不存在");
        }

        //自动上报司机和车辆配置
        String autoUpload = HyCfgUtil.getCfgItem2("zhongjiao_report","auto_upload");

        HyDriver driver = this.driverService.getById(driverId);
        HyVehicle vehicle = this.vehicleService.getById(vehicleId);
        if (!driver.getUploadStatus().equals("1")) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步司机数据");
            }
            log.warn("司机未上报中交中间件，开始同步司机数据, {}", driver.getDriverName());
            Result dResult = this.uploadDriver(driverId);
            if (!dResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return dResult;
            }
        }

        if (!vehicle.getUploadStatus().equals("1")) {
            if (StrUtil.isEmpty(autoUpload) || !autoUpload.equals("1")) {
                return Result.error("请先同步车辆数据");
            }
            log.warn("车辆未上报中交中间件，开始同步车辆数据, {}", vehicle.getVehicleNumber());
            Result vResult = this.uploadVehicle(vehicleId);
            if (!vResult.getCode().equals(CommonConstant.SC_OK_200)) {
                return vResult;
            }
        }

        return Result.OK();
    }


    public Result uploadZjCapitalFlow(String shippingId){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id", shippingId);
        List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(queryWrapper);

        if(CollectionUtils.isEmpty(shippingNoteBills)) {
            throw new JeecgBootException("未找到对应数据");
        }

        HyShippingNote hyShippingNote = hyShippingNoteService.getById(shippingId);
        if (!hyShippingNote.getShippingPayStatus().equals(ShippingPayStatus.支付完成.getValue())) {
            return Result.error("该运单未支付完成");
        }

        CapitalDTO capitalDTO = baseReportService.getCapitalDTO(shippingNoteBills,hyShippingNote);

        try {
            String reportResult = openApiService.reportCapital(capitalDTO);
            if(StringUtils.isNotEmpty(reportResult)){
                JSONObject jsonObject = JSONObject.parseObject(reportResult);
                String resultString = jsonObject.getString("result") != null ? jsonObject.getString("result") : StringUtils.EMPTY ;
                int status = jsonObject.getIntValue("status") ;
                for(HyShippingNoteBill shippingNoteBillDb: shippingNoteBills){
                    shippingNoteBillDb.setUploadStatus(1001  == status ?  "1" : "2");
                    shippingNoteBillDb.setUploadDate(new Date());
                    shippingNoteBillDb.setReportFailureReason(1001  == status  ?  "" : resultString);
                    shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
                }

                hyShippingNoteBillService.updateBatchById(shippingNoteBills);
                if (1001  == status) {
                    return Result.OK("上传成功");
                }
                return Result.error("上传失败");
            }else{
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            for(HyShippingNoteBill shippingNoteBillDb: shippingNoteBills){
                shippingNoteBillDb.setUploadStatus( "2");
                shippingNoteBillDb.setUploadDate(new Date());
                shippingNoteBillDb.setReportFailureReason(e.getMessage());
                shippingNoteBillDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
            }
            hyShippingNoteBillService.updateBatchById(shippingNoteBills);
        }

        return Result.error("上传资金流水失败");
    }


    /**
     * 中交兴路
     * @param hyShippingNote
     * @return
     */
    public Result uploadZjShippingNote(HyShippingNote hyShippingNote) {
        HyShippingNote ShippingNoteDb = hyShippingNoteService.getById(hyShippingNote.getId());
        if (ShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        if("1".equals(ShippingNoteDb.getUploadStatus())){
            return Result.OK();
        }

//            if(!"2".equals(hyShippingNote.getUploadStatus())) {
//                baseReportService.checkShippingNoteRoute(hyShippingNote);
//            }
        WaybillDTO waybillDTO =  baseReportService.shippingNoteTOWaybillDTO(ShippingNoteDb, hyShippingNote.getCompanyId());

        try{
            String reportResult = openApiService.reportWaybill(waybillDTO);
            if (StringUtils.isNotEmpty(reportResult)) {
                JSONObject jsonObject = JSONObject.parseObject(reportResult);
                String resultString = jsonObject.getString("result") != null ? jsonObject.getString("result") : StringUtils.EMPTY ;
                int status = jsonObject.getIntValue("status") ;
                ShippingNoteDb.setUploadStatus(1001  == status   ? "1" : "2");
                ShippingNoteDb.setUploadDate(new Date());
                ShippingNoteDb.setReportFailureReason(1001  == status  ? "" : resultString);
                ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
                hyShippingNoteService.updateById(ShippingNoteDb);
                if (1001  == status) {
                    return Result.OK("上传成功");
                }
                return Result.error("上传失败");
            }else{
                throw new JeecgBootException("未知异常");
            }
        }catch (Exception e){
            ShippingNoteDb.setUploadStatus("2");
            ShippingNoteDb.setUploadDate(new Date());
            ShippingNoteDb.setReportFailureReason(e.getMessage());
            ShippingNoteDb.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
            hyShippingNoteService.updateById(ShippingNoteDb);
        }

        return Result.error("上传运单失败");
    }


    /**
     * 中交兴路
     * @param vehicleId
     * @return
     */
    public Result uploadVehicle(String vehicleId) {
        HyVehicle hyVehiclDb = vehicleService.getById(vehicleId);
        if(hyVehiclDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        HyVehicleReport hyVehicleReport = new HyVehicleReport();

        if (StringUtils.isEmpty(hyVehiclDb.getRoadTransportNumber())) {
            throw new JeecgBootException("车辆道路运输证不能为空！");
        }

        if (!vehicleService.checkRTCNoV2(hyVehiclDb)) {
            throw new JeecgBootException("车辆道路运输证号不正确或者已过期，请修改后重新上传！");
        }

        HyVehicleType hyVehicleType = vehicleService.getHyVehicleType(hyVehiclDb.getVehicleType());
        if (hyVehicleType == null) {
            throw new JeecgBootException("车辆类型不存在,修改后请重新上报！");
        }

        ZjVehicleDTO zjVehicleDTO = new ZjVehicleDTO();
        zjVehicleDTO.setSerialNo(
                hyVehiclDb.getId() + "_" + RandomUtil.randomNumbers(4)
        );
        zjVehicleDTO.setVehicleNumber(hyVehiclDb.getVehicleNumber());
        zjVehicleDTO.setOwner(hyVehiclDb.getOwner());
        zjVehicleDTO.setIssuingOrganizations(hyVehiclDb.getIssuingOrganizations());
        //zjVehicleDTO.setVehicleTonnage(hyVehiclDb.getVehicleTonnage().toString());
        zjVehicleDTO.setVehicleTonnage(
                hyVehiclDb.getVehicleTonnage() != null ? hyVehiclDb.getVehicleTonnage()
                        .setScale(2, BigDecimal.ROUND_DOWN).toString() : "40.00"
        );
        zjVehicleDTO.setRoadTransportCertificateNumber(hyVehiclDb.getRoadTransportNumber());
        zjVehicleDTO.setUseCharacter("货运");
        zjVehicleDTO.setVehiclePlateColorCode(hyVehiclDb.getVehiclePlateColorCode());
        zjVehicleDTO.setVin(hyVehiclDb.getVin());
        zjVehicleDTO.setGrossMass(
                hyVehiclDb.getGrossMass() != null ? hyVehiclDb.getGrossMass()
                        .setScale(2, BigDecimal.ROUND_DOWN).toString() : "48.00"
        );
        zjVehicleDTO.setVehicleEnergyType(hyVehiclDb.getVehicleEnergyType());
        zjVehicleDTO.setVehicleType(hyVehicleType.getValue());
        zjVehicleDTO.setRegisterDate(
                DateUtils.dateToStringNoBar(hyVehiclDb.getRegisterDate())
        );
        zjVehicleDTO.setIssueDate(
                DateUtils.dateToStringNoBar(hyVehiclDb.getIssueDate())
        );

        try{
            String reportResult = openApiService.reportVehicle(zjVehicleDTO);
            if(StringUtils.isNotEmpty(reportResult)){
                JSONObject jsonObject = JSONObject.parseObject(reportResult);
                String resultString = jsonObject.getString("result") != null ? jsonObject.getString("result") : StringUtils.EMPTY ;
                int status = jsonObject.getIntValue("status") ;
                hyVehicleReport.setId(vehicleId);
                hyVehicleReport.setVehicleId(vehicleId);
                hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
                hyVehicleReport.setVehicleUploadStatus(1001  == status? "1" : "2");
                hyVehicleReport.setUploadDate( new Date() );
                hyVehicleReport.setVehicleReportFailureReason(1001  == status ? "" : resultString);
                vehicleReportService.saveVehicleReport(hyVehicleReport);
                if (1001  == status) {
                    return Result.OK("上传成功");
                }
                return Result.error("上传失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            hyVehicleReport.setId(vehicleId);
            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
            hyVehicleReport.setVehicleUploadStatus( "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(e.getMessage());
            vehicleReportService.saveVehicleReport(hyVehicleReport);
        }

        return Result.error("上传车辆失败");
    }



    /**
     * 中交兴路
     * @param driverId
     * @return
     */
    public Result uploadDriver(String driverId){
        HyDriver hyDriver = driverService.getById(driverId);
        if(hyDriver == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        HyDriverReport hyDriverReport = new HyDriverReport();

        //人员从业资格证验证
        if (!driverService.checkQualificationV2(hyDriver)) {
            throw new JeecgBootException("人员从业资格证验证号不正确或者已过期，请修改后重新上传！");
        }

        ZjDriverDTO zjDriverDTO = new ZjDriverDTO();
        zjDriverDTO.setSerialNo(hyDriver.getId() + "_" + RandomUtil.randomNumbers(4));
        zjDriverDTO.setDriverName(hyDriver.getDriverName());
        zjDriverDTO.setDrivingLicense(hyDriver.getIdcard());
        zjDriverDTO.setIssuingOrganizations(hyDriver.getIssuingOrganizations());
        zjDriverDTO.setQualificationCertificate(hyDriver.getIdcard());
        zjDriverDTO.setTelephone(hyDriver.getTelephone());
        zjDriverDTO.setVehicleClass(hyDriver.getVehicleClass());
        zjDriverDTO.setValidPeriodFrom(
                DateUtils.dateToStringNoBar(hyDriver.getValidPeriodFrom())
        );
        zjDriverDTO.setValidPeriodTo(
                DateUtils.dateToStringNoBar(hyDriver.getValidPeriodTo())
        );

        try {
            String reportResult = openApiService.reportDriver(zjDriverDTO);
            if(StringUtils.isNotEmpty(reportResult)){
                JSONObject jsonObject = JSONObject.parseObject(reportResult);
                String resultString = jsonObject.getString("result") != null ? jsonObject.getString("result") : StringUtils.EMPTY ;
                int status = jsonObject.getIntValue("status") ;
                hyDriverReport.setId(driverId);
                hyDriverReport.setDriverId(driverId);
                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
                hyDriverReport.setDriverUploadStatus(1001  == status ? "1" : "2");
                hyDriverReport.setUploadDate( new Date() );
                hyDriverReport.setDriverReportFailureReason(1001  == status ? "" : resultString );
                hyDriverReportService.saveDriverReport(hyDriverReport);
                if (1001  == status) {
                    return Result.OK("上传成功");
                }
                return Result.error(resultString);
            }
        }catch (Exception e){
            e.printStackTrace();
            hyDriverReport.setId(driverId);
            hyDriverReport.setDriverId(driverId);
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_ZJ.getCode());
            hyDriverReport.setDriverUploadStatus( "2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason(e.getMessage());
            hyDriverReportService.saveDriverReport(hyDriverReport);
        }

        return Result.error("上传司机失败");
    }


}
